//
//  UIWebViewJSViewController.m
//  webviewshell
//
//  Created by mac on 2017/8/26.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "UIWebViewJSViewController.h"

@interface UIWebViewJSViewController () <UIWebViewDelegate>

@property (weak, nonatomic) IBOutlet UIWebView *myWeb;



@end

@implementation UIWebViewJSViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.someString = @"UIWebView是iOS最常用的SDK之一，它有一个stringByEvaluatingJavaScriptFromString方法可以将javascript嵌入页面中，通过这个方法我们可以在iOS中与UIWebView中的网页元素交互";
    
    [self loadHtml];
    
    
//    UIWebView Delegate 委托代理
    _myWeb.delegate = self;
    _myWeb.dataDetectorTypes = UIDataDetectorTypeLink;
    //取消右侧，下侧滚动条，去处上下滚动边界的黑色背景
    _myWeb.backgroundColor=[UIColor clearColor];
    for (UIView *_aView in [_myWeb subviews])
    {
        if ([_aView isKindOfClass:[UIScrollView class]])
        {
            [(UIScrollView *)_aView setShowsVerticalScrollIndicator:NO];
            //右侧的滚动条
            
            [(UIScrollView *)_aView setShowsHorizontalScrollIndicator:NO];
            //下侧的滚动条
            
            for (UIView *_inScrollview in _aView.subviews)
            {
                if ([_inScrollview isKindOfClass:[UIImageView class]])
                {
                    _inScrollview.hidden = YES;  //上下滚动出边界时的黑色的图片
                }
            }
        }
    }
    [self.view addSubview:_myWeb];
}

- (void)loadHtml{
//    第一步：创建UIWebView
//    UIWebView *webView;
//    webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 22, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-22)];
    
    
//    第一种
//    加载本地的html
//    NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"需要填写的webview首页" ofType:@"html"];
//    NSString *html = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//    [webView loadHTMLString:html baseURL:baseURL];
    
    
//    第二种
//    加载在线资源http内容
//    NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];  //创建URL
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];    //创建NSURLRequest
//    [webView loadRequest:request];    //加载网页
    
    
//    第三种
//    加载本地的html
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"UIWebViewJS" ofType:@"html"];
    NSURL *url = [NSURL fileURLWithPath:filePath];  //创建URL
    NSURLRequest *request = [NSURLRequest requestWithURL:url];  //创建NSURLRequest
    

    [self.myWeb loadRequest:request];
    
//  UIWebView类内部会管理浏览器的导航动作，通过 goForward 和 goBack 方法你可以控制前进与后退动作
    [self.myWeb goForward];
    [self.myWeb goBack];
    
    
}

/*****************************************************************/
    
    //网页加载之前会调用此方法
    //是否允许加载网页，也可获取js要打开的url，通过截取此url可与js交互
- (BOOL)myWeb:(UIWebView *)myWeb shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    
    NSLog(@"%@", NSStringFromSelector(_cmd));
    NSLog(@"%@", request.URL.absoluteString.stringByRemovingPercentEncoding);
    
    //retrun YES 表示正常加载网页 返回NO 将停止网页加载
    return YES;
}
    
    //开始加载网页调用此方法
- (void)webViewDidStartLoad:(UIWebView *)myWeb
{
    NSLog(@"%@", NSStringFromSelector(_cmd));
}
    
    //网页加载完成调用此方法
- (void)webViewDidFinishLoad:(UIWebView *)myWeb
{
    NSLog(@"%@", NSStringFromSelector(_cmd));
}
    
    //网页加载失败调用此方法
- (void)myWeb:(UIWebView *)myWeb didFailLoadWithError:(NSError *)error
{
    NSLog(@"%@:%@", NSStringFromSelector(_cmd), error.localizedDescription);
}


/*****************************************************************/

//刷新WebView
- (IBAction)loadTouched:(id)sender {
    [self loadHtml];
}


//执行已经存在的js方法
- (IBAction)exeFuncTouched:(id)sender {
    [self.myWeb stringByEvaluatingJavaScriptFromString:@"showAlert('201708281104','情人节快乐')"];
}


//插入html    getElementsByTagName 根据html自带标签定位元素
- (IBAction)insertHtmTouched:(id)sender {
    //插入整个页面内容
    // document.getElementsByTagName('body')[0];"
    
    //替换第一个P元素内容
    NSString *tempString = [NSString stringWithFormat:@"document.getElementsByTagName('p')[0].innerHTML ='%@';",self.someString];
    [self.myWeb stringByEvaluatingJavaScriptFromString:tempString];

}

//修改input值      getElementsByName根据标签名称获取定位元素
- (IBAction)inputButtonTouched:(id)sender {
    NSString *tempString = [NSString stringWithFormat:@"document.getElementsByName('wd')[0].value='%@';",self.someString];
    [self.myWeb stringByEvaluatingJavaScriptFromString:tempString];

}

// 插入html       根据getElementById 定位元素
- (IBAction)insertDivHtml:(id)sender {
    //替换第id为idtest的DIV元素内容
    NSString *tempString2 = [NSString stringWithFormat:@"document.getElementById('idTest').innerHTML ='%@';",self.someString];
    [self.myWeb stringByEvaluatingJavaScriptFromString:tempString2];
}

//插入js 并且执行传值
- (IBAction)insertJSTouched:(id)sender {
    NSString *insertString = [NSString stringWithFormat:
                              @"var script = document.createElement('script');"
                              "script.type = 'text/javascript';"
                              "script.text = \"function jsFunc() { "
                              "var a=document.getElementsByTagName('body')[0];"
                              "alert('%@');"
                              "}\";"
                              "document.getElementsByTagName('head')[0].appendChild(script);", self.someString];
    
    NSLog(@"insert string %@",insertString);
    [self.myWeb stringByEvaluatingJavaScriptFromString:insertString];
    [self.myWeb  stringByEvaluatingJavaScriptFromString:@"jsFunc();"];
}

//替换图片地址
- (IBAction)replaceImgSrc:(id)sender {
    NSString *tempString2 = [NSString stringWithFormat:@"document.getElementsByTagName('img')[0].src ='%@';",@"light_advice.png"];
    [self.myWeb stringByEvaluatingJavaScriptFromString:tempString2];

}

//修改标签字体
- (IBAction)fontTouched:(id)sender {
    NSString *tempString2 = [NSString stringWithFormat:@"document.getElementsByTagName('p')[0].style.fontSize='%@';",@"19px"];
    [self.myWeb stringByEvaluatingJavaScriptFromString:tempString2];
}

//传输json
- (IBAction)jsonTouched:(id)sender {
    NSDictionary *dic =  @{@"key1":@"星期一",@"key2":@"星期二"};
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic
                                                       options:0
                                                         error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSString *testJs = [NSString stringWithFormat:@"testJSON('%@');",jsonString];
    
    [self.myWeb stringByEvaluatingJavaScriptFromString:testJs];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end




//后续：
//使用JavaScriptCore库来做JS交互。
//JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//NSString *textJS = @"showAlert('这里是JS中alert弹出的message')";
//[context evaluateScript:textJS];






















